package com.zretc.news.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jdk.nashorn.internal.runtime.regexp.joni.Regex;

/**
 * Servlet Filter implementation class EncodingFilter
 */
//@WebFilter("/*")
public class MyAccessFilter implements Filter {

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub

		// ServletRequest 转换为 HttpServletRequest
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		// 想得到请求的url地址路径
		System.out.println("URI :" + req.getRequestURI());
		System.out.println("URL :" + req.getRequestURL());
		// req.getRequestURI()
		String uri = req.getRequestURI();

		// 1.如果用户已经登录，没啥好说的，放行
		// pass the request along the filter chain
		if (req.getSession().getAttribute("user") != null) {

			chain.doFilter(request, response);

		} else if (uri.endsWith("login.jsp") || uri.endsWith(".css") ||uri.endsWith(".js")|| uri.endsWith("LoginServlet")) {
			// 登录有关的url 通通放行
			//能不能直接判断非login.jsp的没有登录"都"被重定向
			//简单”择一择“
			chain.doFilter(request, response);

		}
		else {
			// 没有登录 ，请求又是addusers.jsp 地址,告知信息，转发或者重定向到 login.jsp
			res.sendRedirect("login.jsp");

		}

	}

}
